#!/bin/sh /etc/rc.common
# Copyright (C) 2008 OpenWrt.org
START=90

edge() {
	[  -z "$1" ] && return 1
	config_get enabled "$1" enabled
	[ "$enabled" = '1' ] || return 1
	config_get supernode_host "$1" supernode_host
	config_get supernode_port "$1" supernode_port
	[ -z "$supernode_host" -o -z "$supernode_port" ] && return 1
	config_get mode "$1" mode 'static'
	config_get ipaddress "$1" ipaddress
	[ "$mode" = 'dhcp' ] && ipaddress='0.0.0.0'
	config_get netmask "$1" netmask '255.255.255.0'
	config_get device_name "$1" device_name
	config_get community "$1" community
	[ -z "$ipaddress" -o -z "$device_name" -o -z "$community" ] && return 1
	config_get key "$1" key
	config_get_bool route "$1" route '0'
	[ "$route" = "1" -o "$mode" = 'dhcp' ] && args=' -r'
	[ -z "$(echo $supernode_host|grep -o '\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}')" ] && args=$args' -b'
	/usr/sbin/edge -l ${supernode_host}:${supernode_port} -a ${mode}:${ipaddress} -s $netmask -d "$device_name" -c "$community"$([ -n "$key" ] && echo " -k $key")$([ -n "$args" ] && echo "$args")
}


supernode() {
	[  -z "$1" ] && return 1
	config_get enabled "$1" enabled
	[ "$enabled" = '1' ] || return 1
	config_get port "$1" port
	[ -z "$port" ] && return 1
	/usr/sbin/supernode -l $port
}

config_cb() {
	local cfg="$CONFIG_SECTION"
	config_get configname "$cfg" TYPE
	case "$configname" in
		edge)
			edge "$cfg"
			;;
		supernode)
			supernode "$cfg"
			;;
	esac
}

start() {
	config_load n2n
}

stop() {
	killall -9 edge
	killall -9 supernode
}
